//公用变量
// var app = getApp();
//导入阿里云上传js
const Base64 = require('../common/script/Base64.js');
require('../common/script/hmac.js');
require('../common/script/sha1.js');
const Crypto = require('../common/script/crypto.js');

let util = {
  //正式环境
  // userId: '39185681247133793',
  // token: '08f12dff81219284c46db6c2e4a359cf2f30c9b1',
  userId: '',
  token: '',
  userPhone:'',//手机号
  baseurl: 'https://www.exuetech.com', //正式环境
  BindWechat:'/api/v1/user/bind/wechat/',//登录绑定1 解绑2
  loginUrl: '/api/v1/user/login/',//登录
  BindWeiXinPhone:'/api/v1/user/login/wechat/phone/',//微信首次登录绑定手机号
  UpdatePwd:'/api/v1/user/settings/update/',//更新密码，旧密码方式，绑定更换手机号
  //开发环境
  // userId: '39233964824630630',
  // token: '9e49441d0858d41b45148449f39fd033de7c1dff',
  // baseurl: 'http://dev.exuetech.com', //测试地址
  ALIOSS: '/api/v1/utils/aliyun/upload/token/', //OSS认证
  OSSUrl: 'https://xd-resource-1.oss-cn-shanghai.aliyuncs.com/', //bucketName + endpoint
  ALVideoVoucher:'/api/v1/utils/aliyun/video/upload/',//获取阿里云视频凭证
  AccessKeySecret: 'PmlWAr1Mm1VkZ37TQHwa2iwEhggitY',
  OSSAccessKeyId: 'LTAIEK4D4wA6FYkQ',
  timeout: 87600, //这个是上传文件时Policy的失效时间
  defultColor: '#0084ff',
  GetCode:'/api/v1/user/verify/code/',//获取手机验证码
  userPublishWorks: '/api/v1/knowledge/user/page/self/release/', //获取个人已发布作品
  userOffshelve: '/api/v1/knowledge/user/page/self/offshelve/', //获取个人已下架作品
  userDrafts: '/api/v1/knowledge/user/page/self/draft/', //获取个人草稿作品
  userContributeWorks: '/api/v1/knowledge/user/page/self/contribute', //获取个人投稿作品
  cleanDraft: '/api/v1/knowledge/clean/', //知识草稿删除
  KnowledgeHandle: '/api/v1/knowledge/', //创建知识post，修改知识put，删除知识delete
  SectionHandle: '/api/v1/knowledge/section/', //创建知识章节post，修改put，删除delete，获取get
  ReleaseKnowledge: '/api/v1/knowledge/release/', //发布知识
  MessageAllSearch: '/api/v1/message/search/dispatch/', //作品搜索
  CompetitionLists: '/api/v1/knowledge/wk/competition/match-work/', //微课大赛分赛列表查看
  VoteForWork: '/api/v1/knowledge/wk/competition/match-work/contributes/vote/', //投票
  getAcceptWorksList: '/api/v1/comp/works/contribute/', // 查看所有投稿作品
  VoteLists: '/api/v1/knowledge/wk/competition/match-work/contributes/', //微课大赛分赛作品投票列表 
  BatchVoteForWork: '/api/v1/knowledge/wk/competition/match-work/contributes/batch-vote/', //批量投票

  //公用方法
  /* 上传阿里云*/
  uploadOssFile: function(filePath, dir, successc, failc) {
    console.log(filePath)
    // const filePathArr = filePath.split('.')
    const suffix = filePath.substring(filePath.lastIndexOf('.'));//后缀
    const aliyunFileKey = 'MiniProgram/' + util.userId + dir + (new Date().getTime()) + suffix;//lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置，在一个字符串中的指定位置从后向前搜索
    const accessid = util.OSSAccessKeyId;
    const policyBase64 = util.getPolicyBase64();
    const signature = util.getSignature(policyBase64);
    const uploadTask = wx.uploadFile({
      url: util.OSSUrl, //阿里云域名
      filePath: filePath,
      name: 'file', //必须填file
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        'key': aliyunFileKey,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'signature': signature,
        'success_action_status': '200'
      },
      success: function(res) {
        if (res.statusCode != 200) {
          console.log('上传失败')
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          return;
        }
        console.log('上传成功', res)
        successc(util.OSSUrl + aliyunFileKey);
      },
      fail: function(err) {
        failc(err);
      },
    })
    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      if (res.progress == 100){
        wx.hideLoading();
        return;
      }
      wx.showLoading({
        title: res.progress + '%',
      })
    })
    // uploadTask.abort() // 取消上传任务
  },
  getPolicyBase64: function() {
    let date = new Date();
    date.setHours(date.getHours() + util.timeout);
    let srcT = date.toISOString();
    const policyText = {
      "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
      "conditions": [
        ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
      ]
    };

    const policyBase64 = Base64.encode(JSON.stringify(policyText));
    return policyBase64;
  },

  getSignature: function(policyBase64) {
    const accesskey = util.AccessKeySecret;
    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
      asBytes: true
    });
    const signature = Crypto.util.bytesToBase64(bytes);
    return signature;
  },

  //网络请求-用于登录 不带token
  publicRequest: function (url, method, data, success, fail, complete) {
    url = util.baseurl + url;
    wx.showNavigationBarLoading();
    wx.request({
      url: url,
      method: method,
      header: {
        "Content-Type": method === 'GET' ? "json" : "application/json"
      },
      data: data,
      success: function (res) {
        console.log(res.data);
        if (success) {
          if (res.data.code == 0){
            //成功
            //保存token 和用户id
            util.userId = res.data.detail.id
            util.token = res.data.detail.token
            util.userPhone = res.data.detail.phone
          
            success(res.data);
          } else {
            wx.showToast({
              title: util.errorCodeTips(res.data.code),
              icon: 'none'
            })
          }
        }
      },
      fail: function (err) {
        console.log(err);
        if (fail) {
          fail(err);
        }
      },
      complete: function () {
        wx.hideNavigationBarLoading();
        if (complete) {
          complete();
        }
      }
    });
  },
  //网络请求附带token
  publicRequestWithToken: function(url, method, data, success, fail, complete) {
    url = util.baseurl + url;
    wx.showNavigationBarLoading();
    wx.request({
      url: url,
      method: method,
      header: {
        "Content-Type": method === 'GET' ? "json" : "application/json",
        'AUTHORIZATION': 'Token ' + util.token
      },
      data: data,
      success: function(res) {
        console.log(res.data);
        if (success) {
          // success(res.data);
          if (res.data.code == 0) {
            //成功
            success(res.data);
          } else {
            wx.showToast({
              title: util.errorCodeTips(res.data.code),
              icon:'none'
            })
          }
        }
      },
      fail: function(err) {
        console.log(err);
        if (fail) {
          fail(err);
        }
      },
      complete: function() {
        wx.hideNavigationBarLoading();
        if (complete) {
          complete();
        }
      }
    });
  },
  errorCodeTips: function (code) {
    var msg = '';
    switch (code){
      case 40400:
        msg = "请求无效"
        break;
      case 401:
        msg = "未授权"
        break;
      case 500:
        msg = "服务器内部错误"
        break;
      case 502:
        msg = "网关错误"
        break;
      case 40000:
        msg = "很抱歉，网络异常，请稍后再试"
        break;
      case 40001:
        msg = "不能保护敏感词汇，请重新输入"
        break;
      case 40400:
        msg = "很抱歉，网络异常，请稍后再试"
        break;
      case 40401: {
          msg = "尚未登录，请登录后操作";
      }
        break;
      case 40403:
        msg = "操作受限，请稍后再试"
        break;
      case 40404:
        msg = "哎呀，您要找的东西偷偷溜走了，去浏览下其他东西吧。"
        break;
      case 40405:
        msg = "很抱歉，网络异常，请稍后再试"
        break;
      case 40500:
        msg = "很抱歉，网络异常，请稍后再试"
        break;
      case 41001:
        msg = "手机号格式不正确，请重新输入"
        break;
      case 41002:
        msg = "手机号已存在，请确认"
        break;
      case 41003:
        msg = "验证码已使用或已过期，请重新获取"
        break;
      case 41004:
        msg = "该用户不存在，请确认"
        break;
      case 41005:
        msg = "密码输入不一致，请重新输入"
        break;
      case 41006:
        msg = "密码不正确，请确认重新输入"
        break;
      case 41007:
        msg = "非企业认证用户，操作受限，请联系小得认证"
        break;
      case 41008:
        msg = "该小得号已存在，请重新输入"
        break;
      case 41009:
        msg = "该昵称已存在，请重新输入"
        break;
      case 41010:
        msg = "该微信已被绑定，请先解绑或更换微信"
        break;
      case 41011:
        msg = "手机号已被绑定，请解绑或更换手机号"
        break;
      case 41012:
        msg = "未绑定手机号，当前微信不可解绑"
        break;
      case 41013:
        msg = "绑定支付宝失败，请稍后再说"
        break;
      case 41014:
        msg = "已经填写邀请码，不可重复参与，快去邀请其他小伙伴吧获取奖励吧"
        break;
      case 41015:
        msg = "抱歉，不可填写自己的邀请码，快去邀请其他小伙伴吧获取奖励吧"
        break;
      case 41016:
        msg = "未找到邀请码关联的用户，快去与你的小伙伴确认一下吧"
        break;
      case 42001:
        msg = "请求错误，请稍后再试"
        break;
      case 42002:
        msg = "群组名称已存在，请确认重新输入"
        break;
      case 42003:
        msg = "无法关注／取消关注自己"
        break;
      case 42004:
        msg = "为了更好的服务您，小得秘书目前不能取消关注"
        break;
      case 43001:
        msg = "抱歉，该知识已下架"
        break;
      case 43002:
        msg = "当前知识尚未购买，请购买后查看"
        break;
      case 43003:
        msg = "当前知识已参与一项推广活动，暂时无法参与其他推广活动"
        break;
      case 43004:
        msg = "手慢无，红包已被抢完，快去小得福利再看看吧"
        break;
      case 43005:
        msg = "抱歉，免费知识不能参与限免活动"
        break;
      case 43006:
        msg = "该作品是付费内容，请登录后购买查看"
        break;
      case 43012:
        msg = "网络不稳定，视频上传失败，请重新上传"
        break;
      case 45001:
        msg = "余额不足，请前往我的-财富进行充值";
        break;
      case 45002:
        msg = "微信充值失败，请去微信钱包确认是否充值成功";
        break;
      case 45003:
        msg = "没有找到订单号，请确认";
        break;
      case 45004:
        msg = "交易失败，请确认";
        break;
      case -1009:
        msg = "似乎已断开与互联网的连接";
        break;
      case 43010:
        msg = "抱歉，该比赛当前不在投稿时间";
        break;
      case 43011:
        msg = "抱歉，该比赛仅限部分人员投稿";
        break;
    }
    return msg;
  }
}


module.exports = util;